<template>
  <el-dialog :visible.sync="dialogVisible" lock-scroll width="60%">
    <div slot="title" class="header_title">
      <span class="title_span">从Excel导入数据资料</span>
      <div class="title_search">
        <span>先选择要导入的Excel文件，并设置数据项对应关系，然后执行导入</span>
      </div>
    </div>
    <div class="content_div">
      <div class="select_div">
        <div class="line">
          <div class="line_left">
            <p style="margin-right: 6px">请选择Execl文件</p>
            <input class="input1" v-model="fileName" readonly="readonly" />
            <p class="button_top">选择</p>
            <input
              class="input2"
              type="file"
              value="选择"
              ref="fileInput"
              @click="clickUploadFile"
              @change="uploadFile"
            />
          </div>
          <div>
            <p>选择工作表sheet</p>
            <el-select v-model="sheetValue" placeholder="请选择" @change="selectChange(sheetValue)">
              <el-option
                v-for="(item, index) in sheetList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>
        </div>
        <div class="line">
          <div>
            <p>数据项与Excel中数据列的对应关系</p>
          </div>
          <div>
            <el-button :type="corresponding ? 'primary' : ''" @click="onCorresponding">自动对应</el-button>
            <el-button>保存对应关系设置</el-button>
          </div>
        </div>
      </div>
      <div class="table_div">
        <el-table :data="jsonObject" height="100%">
          <el-table-column :resizable="false" label="序号" type="index" width="50"></el-table-column>
          <el-table-column label="是否必填" width="80px">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.isRequired"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="morenName" label="数据项名称" min-width="150px"></el-table-column>
          <el-table-column label="对应Excel中的数据项" min-width="150px">
            <template slot-scope="scope">
              <el-select v-model="scope.row.keyName" clearable placeholder="请选择">
                <el-option
                  v-for="(item1, index1) in keys"
                  :key="index1"
                  :label="item1"
                  :value="item1"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer1_div">
        <div style="display: flex; align-items: center">
          <p>高级选项</p>
          <el-switch v-model="settingValue" active-color="#1A93FA" inactive-color="#D3D2D2"></el-switch>
        </div>
        <el-checkbox v-if="settingValue" v-model="checked1">重复记录不导入（系统根据关键字段自动判断）</el-checkbox>
        <el-checkbox v-if="settingValue" v-model="checked2">必填数据项为空，则该行记录不导入</el-checkbox>
      </div>
      <div class="footer2_div">
        <el-checkbox v-model="checked3">商品不存在新增商品（选中则新增）</el-checkbox>
        <div style="display: flex; align-items: center">
          <p>商品匹配方式</p>
          <el-select v-model="goodsTypeValue" placeholder>
            <el-option
              v-for="item in goodsType"
              :key="item.index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div style="display: flex; align-items: center">
          <el-button type="primary" @click="submitBurruen()">开始导入</el-button>
          <el-button @click="dialogVisible = false">关闭窗口</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { mapGetters } from 'vuex'
import * as XLSX from 'xlsx'
import * as axios from '@/utils/request'
export default {
  name: 'BasicInformation',
  props: ['titles', 'storehouseId', 'url'],
  computed: {
    ...mapGetters(['name']),
  },
  created () {
    this.load()
  },
  watch: {
    dialogVisible (val) {
      if (val) {
        Object.assign(this.$data, this.$options.data())
        this.dialogVisible = true
        this.load()
      }
    },
  },
  data () {
    return {
      dialogVisible: false,
      json: [],
      file: {},
      fileName: '',
      settingValue: true,
      sheetValue: '' /* 选择*/,
      goodsTypeValue: 1 /* 商品类别选择*/,
      keys: [],
      /*  所有的sheet*/
      sheetList: [],
      sheetTitle: {} /* 每个sheet对应一个表头数据 */,
      /*  数据项值*/
      jsonObject: [],
      goodsType: [
        {
          value: 1,
          label: '按商品名称',
        },
        {
          value: 2,
          label: '按商品编码',
        },
        {
          value: 3,
          label: '按商品条码',
        },
        {
          value: 4,
          label: '按商品名称+规格',
        },
      ],
      checked1: false,
      checked2: false,
      checked3: false,
      corresponding: false,
    }
  },
  methods: {
    load () {
      var titleList = Object.values(this.titles)
      for (var i = 0; i < titleList.length; i++) {
        if (titleList[i].isShow) {
          if (titleList[i].zidingyiState) {
            const obj = {
              index: i + 1,
              isRequired: titleList[i].isRequired,
              morenName: titleList[i].zidingyiName ? titleList[i].zidingyiName : titleList[i].morenName,
              props: titleList[i].props,
              keyName: '',
            }
            this.jsonObject.push(obj)
          }
        }
      }
    },
    // 自动对应
    onCorresponding () {
      if (this.keys.length) {
        this.corresponding = true
        for (let i = 0; i < this.jsonObject.length; i++) {
          for (let j = 0; j < this.keys.length; j++) {
            if (this.jsonObject[i].morenName === this.keys[j]) {
              this.jsonObject[i].keyName = this.keys[j]
            }
          }
        }
      } else {
        this.$elMessage({
          showClose: true,
          message: '请先选择Excel文件以及工作表！',
          type: 'error',
          iconClass: 'el-icon-warning-outline',
          duration: 3000,
        })
      }
    },
    clickUploadFile () {
      this.fileName = ''
      this.sheetValue = ''
      this.file = {}
      this.$refs.fileInput.value = null
    },
    uploadFile (e) {
      var that = this
      /* 拿到所导入文件的名字 */
      this.file = e.target.files[0]
      this.fileName = e.target.files[0].name
      this.sheetValue = ''
      let keys = []
      /* 定义reader，存放文件读取方法*/
      const reader = new FileReader()
      /*  启动函数*/
      reader.readAsBinaryString(this.file)
      /*  onload在文件被读取时自动触发*/
      reader.onload = function (e) {
        /* workbook存放excel的所有基本信息*/
        const workbook = XLSX.read(e.target.result, { type: 'binary' })
        /* 定义sheetList中存放excel表格的sheet表，就是最下方的tab*/
        const sheetList = workbook.SheetNames
        that.sheetList = sheetList
        sheetList.forEach(function (y) {
          const worksheet = workbook.Sheets[y]
          const json = XLSX.utils.sheet_to_json(workbook.Sheets[y])
          const formulae = XLSX.utils.sheet_to_formulae(workbook.Sheets[y])
          if (json.length > 0) {
            that.json = json
            json.forEach(function (item) {
              keys = Object.keys(item)
              /* that.keys = keys*/
            })
            that.sheetTitle[y] = keys
          }
        })
      }
    },
    selectChange (v) {
      this.keys = []
      for (var key in this.sheetTitle) {
        if (v == key) {
          this.keys = this.sheetTitle[key]
        }
      }
    },
    submitBurruen () {
      if (this.keys.length) {
        var formData = new FormData()
        formData.append('file', this.file)
        formData.append('noRepeat', this.checked1)
        formData.append('requiredNotNULL', this.checked2)
        formData.append('saveNoGood', this.checked3)
        formData.append('goodsType', this.goodsTypeValue)
        formData.append('lists', JSON.stringify(this.jsonObject))
        formData.append('sheetName', this.sheetValue)
        if (this.storehouseId) {
          formData.append('storehouseId', this.storehouseId)
        }
        this.send(formData)
      } else {
        this.$elMessage({
          showClose: true,
          message: '请先选择Excel文件以及工作表！',
          type: 'error',
          iconClass: 'el-icon-warning-outline',
          duration: 3000,
        })
      }
    },
    send (formData) {
      axios({
        method: 'post',
        url: this.url,
        data: formData,
        dataType: 'json',
        processData: false, // 使数据不做处理
        contentType: false, // 不要设置Content-Type请求头
      })
        .then((res) => {
          if (res.code === 200) {
            this.$emit('importData', res.result)
            this.dialogVisible = false
          } else {
            this.$elMessage({
              showClose: true,
              message: res.message,
              type: 'error',
              iconClass: 'el-icon-warning-outline',
              duration: 3000,
            })
          }
        })
        .catch((resp) => {
          this.dialogVisible = false
        })
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  width: 100%;
  .el-dialog__body {
    padding: 0;
  }
  .el-dialog__header {
    width: 100%;
    height: 0.937559rem;
    box-sizing: border-box;
    padding: 0 0.187512rem 0 0.281268rem;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-dialog__headerbtn {
      position: static;
      .el-icon-close {
        color: #999;
        font-size: 0.48753rem;
      }
    }
  }
  .header_title {
    width: 100%;
    display: flex;
    align-items: center;
    .title_span {
      white-space: nowrap;
      font-size: 0.300019rem;
      color: #666;
      font-weight: 600;
    }
    .title_search {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      padding-left: 0.375023rem;
      > span {
        font-size: 0.225014rem;
        font-family: PingFang SC;
        font-weight: 400;
        color: #999;
      }
    }
  }
}
.content_div {
  width: 100%;
  height: 60vh;
  background: #fff;
  box-sizing: border-box;
  padding: 0 0.281268rem;
  p {
    margin: 0;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #666;
  }
  ::v-deep .el-select {
    width: 120px;
    height: 30px;
    margin-left: 6px;
    .el-input {
      width: 120px;
      height: 30px;
      .el-input__inner {
        width: 100%;
        height: 100%;
        padding-left: 6px;
      }
      .el-select__caret {
        line-height: 30px;
      }
    }
  }
  ::v-deep .el-button {
    width: 150px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #666;
  }
  ::v-deep .el-checkbox {
    display: flex;
    align-items: center;
    .el-checkbox__inner {
      border-color: #c7c6c6;
    }
    .is-checked {
      .el-checkbox__inner {
        background-color: #1b93f9;
        border-color: #1b93f9;
      }
    }
    .el-checkbox__label {
      font-size: 12px;
      color: #666;
      padding-left: 6px;
    }
  }
  .select_div {
    width: 100%;
    height: 90px;
    .line {
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 50%;
      .line_left {
        position: relative;
      }
      > div {
        height: 100%;
        display: flex;
        align-items: center;
        input {
          &:focus {
            outline: none;
            border-color: #1890ff;
            border-right: none;
          }
        }
        .input1 {
          width: 200px;
          height: 30px;
          border: 1px solid #ddd;
          padding: 0 6px;
          font-size: 12px;
          color: #666;
        }
        .button_top {
          width: 60px;
          height: 30px;
          background: #1890ff;
          font-size: 14px;
          color: #fff;
          text-align: center;
          line-height: 30px;
        }
        .input2 {
          position: absolute;
          width: 60px;
          height: 30px;
          right: 0;
          opacity: 0;
        }
        ::v-deep .el-button--primary {
          background-color: #1890ff;
          color: #fff;
        }
      }
    }
  }
  .table_div {
    width: 100%;
    height: calc(100% - 90px - 40px - 60px);
    background: pink;
    ::v-deep .el-table {
      border: 1px solid #e3e3e3;
      border-bottom: none;
      box-sizing: border-box;
      th,
      td {
        padding: 0;
        color: #666;
        box-sizing: border-box;
        border-right: 1px solid #e3e3e3;
        .cell {
          height: 0.562535rem;
          display: flex;
          align-items: center;
          font-size: 0.225014rem;
          .el-select {
            width: 97%;
            margin-left: 0;
            display: flex;
            align-items: center;
            .el-input--suffix {
              width: 100%;
              height: 26px;
            }
            .el-select__caret {
              line-height: 26px;
            }
          }
        }
        &:first-child {
          .cell {
            justify-content: center;
          }
        }
        &:nth-child(2) {
          .cell {
            justify-content: center;
          }
        }
      }
      th {
        .cell {
          background: #ededed;
          justify-content: center;
        }
      }
      .el-table__body tr:hover > td {
        background: #e3f6ff;
      }
      .el-table__footer-wrapper {
        td {
          background: #f4f4f4;
          border: none;
        }
      }
      //滚动条的宽度
      ::-webkit-scrollbar {
        width: 10px;
        height: 10px;
        background-color: #e5e5e5;
      }
      //滚动条的滑块
      ::-webkit-scrollbar-thumb {
        background-color: #c9c9c9;
      }
    }
  }
  .footer1_div {
    width: 100%;
    height: 40px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #eeeeee;
    p {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 600;
      margin-right: 6px;
    }
    ::v-deep .el-switch {
      width: 30px;
      flex: 0;
      .el-switch__core {
        width: 30px;
        height: 15px;
      }
      .el-switch__core::after {
        width: 0.243765rem;
        height: 0.243765rem;
        top: 0;
        right: 0;
      }
    }
    ::v-deep .is-checked {
      .el-switch__core::after {
        margin-left: -14px;
      }
    }
  }
  .footer2_div {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    ::v-deep .el-button {
      width: 100px;
    }
    ::v-deep .el-button--primary {
      background-color: #1890ff;
      color: #fff;
    }
  }
}
</style>
